package com.calendar.MaiDong;

import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Color;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.uimanager.UIManagerModule;
import com.facebook.react.uimanager.events.Event;
import com.facebook.react.uimanager.events.EventDispatcher;
import com.facebook.react.uimanager.events.RCTEventEmitter;
import com.calendar.MaiDong.calendar.Miui10Calendar;
import com.calendar.MaiDong.entity.NDate;
import com.calendar.MaiDong.listener.OnCalendarChangedListener;
import com.calendar.MaiDong.listener.OnClickDisableDateListener;
import com.calendar.MaiDong.utils.Attrs;
import com.calendar.MaiDong.view.WeekBar;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CalendarView extends LinearLayout {

//    view上的组件
    View topView;
    TextView tv_month;
    TextView tv_year;
    TextView tv_month_year;
//    星期view
    WeekBar weekBar;
//    日历
    Miui10Calendar miui10Calendar;
//    事件字典
    Map<String,Integer> dateMap;
//    自定义属性
    CustomPainter customPainter;
    Context context;

//    需要选中的日期数组
    private ReadableArray dateArray;
//    日历长
    private float width;
//    日历高
    private float height;
//    颜色都为16进制
//    当天的颜色
    private String todayColor;
//    选中的颜色
    private String selectionColor;
//    含有事件的日期默认颜色
    private String eventDefaultColor;
//    星期几的颜色
    private String weekdayTextColor;
//    头部标题颜色
    private String headerTitleColor;
//    日历背景颜色
    private String calendarBackgroundColor;
//    标题默认颜色
    private String titleDefaultColor;
//    是否显示阴历
    private boolean showLunar;
//    是否是中文
    private boolean chinese;
//    是否显示事件
    private boolean showEvent;
//    是否多选
    private boolean allowsMultipleSelection;
//    是否显示正方形
    private boolean square;
//    是否显示节假日
    private boolean showHoliday;
//    最小和最大日期
    private ReadableArray minAndMaxDate;

    final EventDispatcher mEventDispatcher;

    //    初始化
    public CalendarView(Context context){
        this(context,null);
    }

    public CalendarView(Context context,AttributeSet attrs){
        this(context,attrs,0);
    }

    public CalendarView(Context context,AttributeSet attrs,int defStyleAttr){
        super(context,attrs,defStyleAttr);
        LayoutInflater.from(context).inflate(R.layout.calendar_view_layout,this);
        this.context = context;
        customPainter = new CustomPainter(context);
        mEventDispatcher = ((ReactContext) getContext()).getNativeModule(UIManagerModule.class).getEventDispatcher();
        dateMap = new HashMap<>();
        loadCustomView(context);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    //    加载日历上的控件
    public void loadCustomView(final Context context){
        tv_month = findViewById(R.id.tv_month);
        tv_year = findViewById(R.id.tv_year);
        tv_month_year = findViewById(R.id.tv_month_year);
        weekBar = findViewById(R.id.weekBar);
        topView = findViewById(R.id.topView);
        miui10Calendar = findViewById(R.id.miui10Calendar);
        miui10Calendar.setCalendarPainter(customPainter);
        miui10Calendar.setOnCalendarChangedListener(new OnCalendarChangedListener() {
            @Override
            public void onCalendarDateChanged(NDate date, boolean isClick) {
                Integer yearCount = date.localDate.getYear();
                Integer monthCount = date.localDate.getMonthOfYear()+1;
                if(miui10Calendar.getState() == Attrs.MONTH) {
                    if (monthCount == 2) {
                        yearCount = yearCount - 1;
                    }
                    if (monthCount == 13) {
                        monthCount = 1;
                    }
                }
                tv_year.setText(yearCount+"");
                tv_month.setText(monthCount+"月");
                tv_month_year.setText(date.localDate.getMonthOfYear()+"月"+" "+date.localDate.getYear()+"");
                if(isClick){
                    uploadDateString(date.localDate.toString());
                }
            }

            @Override
            public void onCalendarStateChanged(boolean isMonthSate) {
                MyLog.d("OnCalendarChangedListener:::" + isMonthSate);
                uploadCalendarHeight(px2dip(context,miui10Calendar.childLayout.getY()));
            }
        });
        miui10Calendar.setOnClickDisableDateListener(new OnClickDisableDateListener() {
            @Override
            public void onClickDisableDate(NDate nDate) {
            }
        });
    }

    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f)+80;
    }

//    用与和将日期传给RN的方法
    public void uploadDateString(final String date){
        mEventDispatcher.dispatchEvent(new Event(getId()) {
            @Override
            public String getEventName() {
                return "ClickDate";
            }

            @Override
            public void dispatch(RCTEventEmitter rctEventEmitter) {
                WritableMap eventMap = Arguments.createMap();
                eventMap.putString("date",date);
                rctEventEmitter.receiveEvent(getViewTag(),getEventName(),eventMap);
            }
        });
    }

//    给RN传递高度
    public void uploadCalendarHeight(final float calendarHeight){
        mEventDispatcher.dispatchEvent(new Event(getId()) {
            @Override
            public String getEventName() {
                return "CalendarHeight";
            }

            @Override
            public void dispatch(RCTEventEmitter rctEventEmitter) {
                WritableMap eventMap = Arguments.createMap();
                eventMap.putDouble("calendarHeight",calendarHeight);
                rctEventEmitter.receiveEvent(getViewTag(),getEventName(),eventMap);
            }
        });
    }

//    触摸事件
    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {

        if (miui10Calendar.isInflateFinish) {
            switch (ev.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    miui10Calendar.dowmY = (int) ev.getY();
                    miui10Calendar.downX = (int) ev.getX();
                    miui10Calendar.lastY = miui10Calendar.dowmY;
                    break;
                case MotionEvent.ACTION_MOVE:
                    int y = (int) ev.getY();
                    int absY = Math.abs(miui10Calendar.dowmY - y);
                    if (absY > miui10Calendar.verticalY) {
                        //onInterceptTouchEvent返回true，触摸事件交给当前的onTouchEvent处理
                        return true;
                    }
                    break;
            }
        }
        return super.onInterceptTouchEvent(ev);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_MOVE:
                int y = (int) event.getY();
                int dy = miui10Calendar.lastY - y;

                if (miui10Calendar.isFirstScroll) {
                    // 防止第一次的偏移量过大
                    if (dy > miui10Calendar.verticalY) {
                        dy = dy - miui10Calendar.verticalY;
                    } else if (dy < -miui10Calendar.verticalY) {
                        dy = dy + miui10Calendar.verticalY;
                    }
                    miui10Calendar.isFirstScroll = false;
                }

                // 跟随手势滑动
                miui10Calendar.gestureMove(dy, null);
                miui10Calendar.lastY = y;
                break;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
                miui10Calendar.isFirstScroll = true;
                miui10Calendar.autoScroll();
                break;
        }
        return true;
    }

    public void changeViewHeight(int changeHeight,boolean isWeek){
        final ValueAnimator animator;
        if(isWeek){
            animator = ValueAnimator.ofInt((int) this.height,changeHeight);
        }
        else {
            animator = ValueAnimator.ofInt(changeHeight,(int)this.height);
        }
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                int h = (Integer)animator.getAnimatedValue();
                getLayoutParams().height = h;
                requestLayout();
            }
        });
        animator.setDuration(1000);
        animator.start();
    }

    //    上个月
    public void jumpToLastMonth(){
        miui10Calendar.toLastPager();
    }

//    回到今天
    public void backToToday(){
        miui10Calendar.toToday();
    }

//    跳转到指定日期
    public void jumpToSpecifiedDate(String dateString){
        miui10Calendar.jumpDate(dateString);
    }

//    下个月
    public void jumpToNextMonth(){
        miui10Calendar.toNextPager();
    }

//    周显示
    public void showWeek(){
        miui10Calendar.toWeek();
    }

//    月显示
    public void showMonth(){
        miui10Calendar.toMonth();
    }

//    自定义View放在RN上时要实现重新布局
    @Override
    public void requestLayout() {
        super.requestLayout();
        post(new Runnable(){
            @Override
            public void run() {
                measure(
                        MeasureSpec.makeMeasureSpec(getWidth(), MeasureSpec.EXACTLY),
                        MeasureSpec.makeMeasureSpec(getHeight(), MeasureSpec.EXACTLY)
                );
                layout(getLeft(), getTop(), getRight(), getBottom());
            }
        });
    }

    //    从RN传回来的参数
    public void setDateArray(ReadableArray dateArray){
        this.dateArray = dateArray;
        List<String> localDates = new ArrayList<>();
        for(int i = 0 ; i < dateArray.size() ; i++){
            localDates.add(dateArray.getString(i));
        }
        customPainter.setPointList(localDates);
    }

    public void setWidth(float width) {
        this.width = width;
    }

    public void setHeight(float height) {
        this.height = height;
    }


    public void setTodayColor(String todayColor) {
        this.todayColor = todayColor;
        customPainter.setTodayColor(todayColor);
    }

    public void setSelectionColor(String selectionColor) {
        this.selectionColor = selectionColor;
        customPainter.setSelectionColor(selectionColor);
    }

    public void setEventDefaultColor(String eventDefaultColor) {
        this.eventDefaultColor = eventDefaultColor;
        customPainter.setEventDefaultColor(eventDefaultColor);
    }

    public void setWeekdayTextColor(String weekdayTextColor) {
        this.weekdayTextColor = weekdayTextColor;
        weekBar.setTextColor(Color.parseColor(weekdayTextColor));
    }

    public void setHeaderTitleColor(String headerTitleColor) {
        this.headerTitleColor = headerTitleColor;
        tv_month.setTextColor(Color.parseColor(headerTitleColor));
        tv_year.setTextColor(Color.parseColor(headerTitleColor));
        tv_month_year.setTextColor(Color.parseColor(headerTitleColor));
    }

    public void setCalendarBackgroundColor(String calendarBackgroundColor) {
        this.calendarBackgroundColor = calendarBackgroundColor;
        miui10Calendar.setBackgroundColor(Color.parseColor(calendarBackgroundColor));
        customPainter.setCalendarBackgroundColor(calendarBackgroundColor);
        topView.setBackgroundColor(Color.parseColor(calendarBackgroundColor));
        weekBar.setBackgroundColor(Color.parseColor(calendarBackgroundColor));
    }

    public void setTitleDefaultColor(String titleDefaultColor) {
        this.titleDefaultColor = titleDefaultColor;
        tv_month.setTextColor(Color.parseColor(titleDefaultColor));
        tv_year.setTextColor(Color.parseColor(titleDefaultColor));
        tv_month_year.setTextColor(Color.parseColor(titleDefaultColor));
    }

    public void setShowLunar(boolean showLunar) {
        this.showLunar = showLunar;
        customPainter.setShowLunar(showLunar);
    }

    public void setChinese(boolean chinese) {
        this.chinese = chinese;
    }

    public void setShowEvent(boolean showEvent) {
        this.showEvent = showEvent;
    }

    public void setAllowsMultipleSelection(boolean allowsMultipleSelection) {
        this.allowsMultipleSelection = allowsMultipleSelection;
    }

    public void setSquare(boolean square) {
        this.square = square;
    }

    public void setShowHoliday(boolean showHoliday) {
        this.showHoliday = showHoliday;
        customPainter.setShowHoliday(showHoliday);
    }

    public void setMinAndMaxDate(ReadableArray minAndMaxDate){
        this.minAndMaxDate = minAndMaxDate;
        miui10Calendar.setDateInterval(minAndMaxDate.getString(0),minAndMaxDate.getString(1));
    }
}
